package com.zx.deploy.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.io.FileUtils;

/**
 * 
 * @Description:计算文件md5
 * @author jbyu
 * @date 2018年1月31日 下午3:46:35
 *
 */
public class FileMD5Util {
	
	public final static String[] strHex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e",
			"f" };

	
	/**
	 * 
	* @Description: 文件文件路径生成md5
	* @param path
	* @return     
	* @throws 
	* @author    jbyu
	 */
	public static String getMD5ByFile(String path) {
		StringBuffer sb = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] b = md.digest(FileUtils.readFileToByteArray(new File(path)));
			for (int i = 0; i < b.length; i++) {
				int d = b[i];
				if (d < 0) {
					d += 256;
				}
				int d1 = d / 16;
				int d2 = d % 16;
				sb.append(strHex[d1] + strHex[d2]);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	
	/**
	 * 
	* @Description: 根据byte生成md5
	* @param data
	* @
	* @return     
	* @throws 
	* @author    jbyu
	 */
	public static String getMD5ByByte(byte[] data) {
		StringBuffer sb = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] b = md.digest(data);
			for (int i = 0; i < b.length; i++) {
				int d = b[i];
				if (d < 0) {
					d += 256;
				}
				int d1 = d / 16;
				int d2 = d % 16;
				sb.append(strHex[d1] + strHex[d2]);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	
	/**
	 * 
	* @Description: 大文件分段读取生成md5
	* @param path
	* @return     
	* @throws 
	* @author    jbyu
	 */
	public static String getMD5BigFile(String path) {
		String bi = null;
		try {
			byte[] buffer = new byte[8192];
			int len = 0;
			MessageDigest md = MessageDigest.getInstance("MD5");
			File f = new File(path);
			FileInputStream fis = new FileInputStream(f);
			while ((len = fis.read(buffer)) != -1) {
				md.update(buffer, 0, len);
			}
			fis.close();
			byte[] b = md.digest();
			bi=toHex(b);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bi;
	}
	
	public static String toHex(byte[] buffer) {
		StringBuffer sb = new StringBuffer(buffer.length * 2);
		for (int i = 0; i < buffer.length; i++) {
			sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
			sb.append(Character.forDigit(buffer[i] & 15, 16));
		}
		return sb.toString();
	}


}
